import mitt from "mitt"
import { SelectionModel, SelectionType, TextModel } from "../models"

export class RenderView{
    textModel_: TextModel
    viewContainer_: HTMLElement
    getSpacers: string = ''
    selectionModel_: SelectionModel
    emitter = mitt()
    constructor(textModel: TextModel,viewContainer: HTMLElement,selectionModel: SelectionModel){
        this.textModel_ = textModel
        this.viewContainer_ = viewContainer
        this.selectionModel_ = selectionModel
        this.addEventListener()

    }
    render(){
        this.viewContainer_.innerHTML = this.textModel_.getSpacers()
        setTimeout(() => {
            this.updateDomSelection()
        }, 0)
    }
    updateDomSelection(){
        const domSelection = window.getSelection()
        if (domSelection) {
            const originSelection: SelectionType | null = this.selectionModel_.getSelection();
            const anchor = originSelection?.anchor || 0;
            const range = window.document.createRange();
            console.log(this.viewContainer_.childNodes)
            range.setStart(this.viewContainer_.childNodes[0], anchor);
            range.setEnd(this.viewContainer_.childNodes[0], anchor);
            domSelection.removeAllRanges();
            domSelection.addRange(range);
        }

    }
    domSelectionChangeHandler(){
        const domSelection = window.getSelection()
        if(domSelection){
            this.emitter.emit('selection-change',{anchor:domSelection.anchorOffset,focus:domSelection.focusOffset})
        }

    }
    addEventListener(){
        this.textModel_.emitter.on('text-change',this.render.bind(this))
        window.document.addEventListener('selectionchange', this.domSelectionChangeHandler.bind(this))
    }
}